//
//  ICPasswordInputView.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/14.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICPasswordInputView.h"
#import "ICHeaderFile.h"

#define kNumCount 6

@interface ICPasswordInputView () <UITextFieldDelegate>

/** 密码框标题 */
@property (nonatomic, strong) UILabel *passwordTitle;
/** 分割线 */
@property (nonatomic, strong) UIImageView *separatorLine;
/** 密码输入框 */
@property (nonatomic, strong) UIImageView *passwordTextfieldView;
/** 关闭按钮 */
@property (nonatomic, strong) UIButton *closeButton;
/** 忘记密码 */
@property (nonatomic, strong) UIButton *forgetPWDButton;
/** 确认按钮 */
@property (nonatomic, strong) UIButton *doneButton;
/** 保存用户输入的数字 */
@property (nonatomic, strong) NSMutableArray *inputNumArray;
/** 保存密码数字 */
@property (nonatomic, copy) NSString *tempStr;

@end

@implementation ICPasswordInputView

- (void)dealloc {
    self.closeBlock = nil;
    self.forgetPWDBlock = nil;
    self.doneBlock = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    BOOL isPlus = (APP_Frame_Height == 736);
    [self.passwordTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.top.equalTo(self.mas_top);
        make.height.mas_equalTo(isPlus ? 50 : 45);
    }];
    [self.separatorLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.passwordTitle.mas_bottom);
        make.right.equalTo(self.mas_right);
        make.height.mas_equalTo(1);
    }];
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.mas_top);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(45);
    }];
    [self.workPointLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.top.equalTo(self.passwordTitle.mas_bottom);
        make.height.mas_equalTo(isPlus ? 40 : 35);
    }];
    [self.passwordTextfieldView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(20);
        make.top.equalTo(self.workPointLabel.mas_bottom);
        make.right.equalTo(self.mas_right).offset(-20);
    }];
    [self.forgetPWDButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.passwordTextfieldView.mas_left);
        make.top.equalTo(self.passwordTextfieldView.mas_bottom);
        make.height.equalTo(isPlus ? self.passwordTitle.mas_height : self.passwordTextfieldView.mas_height);
    }];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.passwordTextfieldView.mas_left);
        make.bottom.equalTo(self.mas_bottom).offset(-13);
        make.right.equalTo(self.passwordTextfieldView.mas_right);
        make.height.mas_equalTo(40);
    }];
}

- (void)close {
    self.tempStr = nil;
    [self removeFromSuperview];
}

- (void)clearThePassword {
    self.tempStr = nil;
    [self.inputNumArray removeAllObjects];
    [self textFieldTextChanged];
    [self setNeedsDisplay];
    self.txfResponsder.delegate = self;
}

#pragma mark - Event response

- (void)closeBtnClicked:(UIButton *)sender {
    [self close];
    if (self.closeBlock) {
        self.closeBlock();
    }
    [self.inputNumArray removeAllObjects];
}

- (void)forgetPWDBtnClicked:(UIButton *)sender {
    if (self.forgetPWDBlock) {
        self.forgetPWDBlock();
    }
}

- (void)doneBtnClicked:(UIButton *)sender {
    if (self.doneBlock) {
        self.doneBlock(self.tempStr);
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (!self.tempStr) {
        self.tempStr = string;
    } else {
        self.tempStr = [NSString stringWithFormat:@"%@%@",self.tempStr,string];
    }
    
    if ([string isEqualToString:@""]) {
        // 删除最后一个字符串
        [self.inputNumArray removeLastObject];
        [self setNeedsDisplay];
        
        if (self.tempStr.length > 0) {
            NSString *lastStr = [self.tempStr substringToIndex:[self.tempStr length] - 1];
            self.tempStr = lastStr;
        }
    } else {
        // 添加一个字符串
        if (self.tempStr.length <= kNumCount) {
            [self.inputNumArray addObject:string];
            [self setNeedsDisplay];
        }else {
            NSString *lastStr = [self.tempStr substringToIndex:6];
            self.tempStr = lastStr;
        }
    }
    [self textFieldTextChanged];
    
    return YES;
}

- (void)textFieldTextChanged {
    self.doneButton.enabled = (self.inputNumArray.count == kNumCount);
    if (self.doneButton.isEnabled) {
        [self.doneButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
    }else {
        [self.doneButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
    }
}

#pragma mrak - drawRect

- (void)drawRect:(CGRect)rect {
    CGRect textfieldFrame = self.passwordTextfieldView.frame;
    
    // 画背景图
    UIImage *imgBackground = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_bg"];
    [imgBackground drawInRect:rect];
    
    // 画格子
    UIImage *imgTextfield = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_textfield"];
    [imgTextfield drawInRect:textfieldFrame];
    
    // 画点
    UIImage *pointImage = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_point"];
    CGFloat pointW = pointImage.size.width;
    CGFloat pointH = pointImage.size.height;
    CGFloat pointY = textfieldFrame.origin.y + (textfieldFrame.size.height - pointH) * 0.5;
    __block CGFloat pointX;
    
    // 一格的宽度
    CGFloat cellW = textfieldFrame.size.width / kNumCount;
    CGFloat padding = (cellW - pointW) * 0.5;
    [self.inputNumArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        pointX = textfieldFrame.origin.x + (2 * idx + 1) * padding + idx * pointW;
        [pointImage drawInRect:CGRectMake(pointX, pointY, pointW, pointH)];
    }];
}

#pragma mark  - Getter

- (UILabel *)passwordTitle {
    if (!_passwordTitle) {
        _passwordTitle = [[UILabel alloc] init];
        _passwordTitle.font = [UIFont systemFontOfSize:15];
        _passwordTitle.text = @"请输入支付密码";
        _passwordTitle.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_passwordTitle];
    }
    return _passwordTitle;
}

- (UIImageView *)separatorLine {
    if (!_separatorLine) {
        _separatorLine = [[UIImageView alloc] init];
        _separatorLine.backgroundColor = ICRGB(0xd2d2d2);
        [self addSubview:_separatorLine];
    }
    return _separatorLine;
}

- (UILabel *)workPointLabel {
    if (!_workPointLabel) {
        _workPointLabel = [[UILabel alloc] init];
        _workPointLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_workPointLabel];
    }
    return _workPointLabel;
}

- (UIImageView *)passwordTextfieldView {
    if (!_passwordTextfieldView) {
        _passwordTextfieldView = [[UIImageView alloc] init];
        _passwordTextfieldView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_textfield"];
        [self addSubview:_passwordTextfieldView];
        _passwordTextfieldView.hidden = YES;
    }
    return _passwordTextfieldView;
}

- (UITextField *)txfResponsder {
    if (!_txfResponsder) {
        _txfResponsder = [[UITextField alloc] init];
        _txfResponsder.delegate = self;
        _txfResponsder.keyboardType = UIKeyboardTypeNumberPad;
        [self addSubview:_txfResponsder];
    }
    return _txfResponsder;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_closeButton];
    }
    return _closeButton;
}

- (UIButton *)forgetPWDButton {
    if (!_forgetPWDButton) {
        _forgetPWDButton = [[UIButton alloc] init];
        [_forgetPWDButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
        [_forgetPWDButton setTitleColor:ICRGB(0x0091ea) forState:UIControlStateNormal];
        _forgetPWDButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_forgetPWDButton addTarget:self action:@selector(forgetPWDBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_forgetPWDButton];
        [_forgetPWDButton sizeToFit];
    }
    return _forgetPWDButton;
}

- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneButton setTitle:@"确认" forState:UIControlStateNormal];
        [_doneButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_doneButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_password_done"] forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_doneButton];
        _doneButton.enabled = NO;
    }
    return _doneButton;
}

- (NSMutableArray *)inputNumArray {
    if (!_inputNumArray) {
        _inputNumArray = [NSMutableArray array];
    }
    return _inputNumArray;
}

@end
